<?php
/**
 * 记录Access日志
 */
declare(strict_types=1);

namespace Apps\Http\Hooks;

use Libraries\Dispatcher;
use Libraries\Bases\HookBase;
use Libraries\File;
use Libraries\Helper;

class SaveAccessLog extends HookBase
{
    /**
     * Hook
     * @param string $strCtrlAction
     * @param string $strHookType
     * @param array $arrParam
     * @return void
     */
    public function run(string $strCtrlAction = '', string $strHookType = Dispatcher::HOOK_AFTER, array $arrParam = []): void
    {
        global $objHttpServer;
        $arrRe = [];
        $floNow = microtime(true);
        $arrRe[] = round($floNow - $this->objCtrl->arrServer['request_time_float'], 5);
        $floNow = intval($floNow);
        $arrRe[] = $this->objCtrl->strRemoteIp;
        $arrRe[] = date('Y-m-d H:i:s O', intval($this->objCtrl->arrServer['request_time_float']));
        $arrRe[] = $this->objCtrl->strRequestMethod;
        $strQueryString = $this->objCtrl->arrServer['query_string'] ?? '';
        $strQueryString && $strQueryString = '?' . $strQueryString;
        $arrRe[] = $this->objCtrl->arrServer['path_info'] . $strQueryString;
        $arrRe[] = $this->objCtrl->arrServer['server_protocol'] ?? '';
        $arrRe[] = $this->objCtrl->arrHeader['user-agent'] ?? '';
        $arrRe[] = $this->objCtrl->arrHeader['referer'] ?? '';
        $strFile = CACHES_PATH . '/access_log/' . date('ymd', $floNow) . '/' . $this->objCtrl->arrServer['server_port'] . '_' . $objHttpServer->worker_id . '.log';
        File::coWrite($strFile, Helper::jsonEncode($arrRe) . PHP_EOL, 'a');
    }
}
